<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>21canvas面向对象实现随机小球运动</title>
</head>
<body>
    <canvas id="oCanvas"></canvas>
</body>

<script>
    // 获取canvas对象
    var canvas = document.getElementById("oCanvas");
    // 通过canvas对象获取 2d对象（画笔对象）
    var ctx = canvas.getContext('2d');


    canvas.width = document.documentElement.clientWidth;
    canvas.height = document.documentElement.clientHeight;

    // 创建一个存储球的数组
    var BallArr = [];
    // 创建一个构造函数
    function Ball(color){
        this.x = parseInt(Math.random()*canvas.width);
        this.y = parseInt(Math.random()*canvas.height);
        this.r = 10;
        this.color = color;

        // 设置移动的距离
        this.dx = parseInt(Math.random()*10)-5;
        console.log(this.dx);
        this.dy = parseInt(Math.random()*10)-5;
        console.log(this.dy);
        
        // 将构造函数创建的对象 压入数组中
        BallArr.push(this);
    }
    // 绘制一个小球
    Ball.prototype.render = function(){
        ctx.beginPath();
        ctx.fillStyle=this.color;
        ctx.arc(this.x,this.y,this.r,0,2*Math.PI);
        ctx.fill();
    }

    // 更新数据
    Ball.prototype.update = function(){
        // 更新圆心的坐标
        this.x+=this.dx;
        this.y+=this.dy;
        if(this.x < 0 || this.x > canvas.width){
            this.dx = -this.dx;
        }
        if(this.y < 0 || this.y > canvas.height ){
            this.dy = -this.dy;
        }
    }
    // 实例化二十个小球
    for(var i = 0 ; i < 2000 ; i++){
        var ball = new Ball('red');
        // console.log(ball);
    }

    // 设置一个定时器
    setInterval(function(){

        // 清除画布
        ctx.clearRect(0,0,canvas.width,canvas.height);
        
        for(var k = 0, len = BallArr.length ; k < len ;k++){
            // 更新数据
                BallArr[k].update();
            // 重新绘制
                BallArr[k].render();
        }

    },300)






    

    














</script>
</html>